package rabbitas {
	import flash.display.Stage;
	import rabbitas.ns.Nodes;
	import flash.events.Event;
	import mx.collections.ArrayCollection;
	import flash.events.IEventDispatcher;
	import flash.utils.Dictionary;
	/**
	 * @author martindyrby
	 */
	public class EventManager {
		private var eventRegistry:Dictionary;
		private var stage:Stage;
		public static function isEventAttribute(name : String) : Boolean {
			return name.substr(0,2) == "on" && name.length > 2;
		}

		public static function getNameFromEventAttribute(name : String) : String {
			return name.substr(2, 1).toLowerCase() + name.substr(3);
		}		
		
		
		
		
		public function EventManager(stage:Stage) {
			this.stage = stage;
			eventRegistry = new Dictionary(true);
		}
		
		public function setupEvents(def:XML, instance:IEventDispatcher) : void {
			/*
			var events:XMLList = def.child(Nodes.eventQName);
			
			for(var i:int = 0; i < events.length(); i++) {
				var event:XML =events[i];
				var eventName:String = event.@name;
				var eventHandler:String = event.@handler;
				try {				
					stage.addEventListener(eventName, instance[eventHandler], false, 0, true);
				} catch (e:Error) {
					RabbitLogger.error("Error adding event listener.");
					RabbitLogger.error(e);
				}
			}
			*/
			
			var attributes:XMLList = def.attributes();
			for each (var attribute:XML in attributes) {
				var attrName : String = attribute.name();

				if (isEventAttribute(attrName)) {
					registerEventWithNamedHandler(instance, getNameFromEventAttribute(attrName), def.@[attrName]);
				}
			}
			 
		}

		public function registerEventWithNamedHandler(instance : IEventDispatcher, eventName : String, handler : String) : void {

			var f:Function = instance[handler];
			
			registerEvent(instance, eventName, f); 
		}

		private function registerEvent(instance : IEventDispatcher, eventName : String, handler : Function) : void {
			initEventRegistry(instance, eventName);
			
			var handlers:Vector.<Function> = eventRegistry[instance][eventName];
			
			handlers.push(handler);

			instance.addEventListener(eventName, listener);
		}

		private function listener(event : Event) : void {
			var handlers : Vector.<Function> = eventRegistry[event.currentTarget][event.type];
			for each(var handler:Function in handlers) {
				try {
					handler.apply();
				}catch(e:Error) {
					handler.apply(null, [event]);
				}
				
			}
			
			eventRegistry[event.currentTarget][event.type] = null;
		}

		private function initEventRegistry(instance : IEventDispatcher, eventName : String) : void {
			if (eventRegistry[instance] == null) {
				eventRegistry[instance] = new Object();
			}

			if (eventRegistry[instance][eventName] == null) {
				eventRegistry[instance][eventName] = new Vector.<Function>();
			}
		}
	}
}
